package com.woldier.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 通用异常处理器
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})  //controller增强(扫描,RestController,Controller注解)
@ResponseBody //返回json格式数据
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> sqlExceptionHandler(SQLIntegrityConstraintViolationException msg){


        String message = msg.getMessage();
        /**
         * 检测是否是账号重复
         * */
        if(message.contains("Duplicate entry")){
            /*分割 截取到想要的信息*/
            String[] s = message.split("\'");
            return R.error(s[1]+"已存在");
        }


        log.error("{}",msg.getMessage());
        return R.error("global-出现错误");
    }


    @ExceptionHandler(MyException.class)
    public R<String> sqlExceptionHandler(MyException msg){
        log.error("{}",msg.getMessage());
        return R.error(msg.getMessage());
    }


}
